<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\AdminAttachment;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AdminAttachmentController extends AdminController
{
    use HasUploadedFile;
    /**
     * 自定义文件上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|mixed|void
     */
    public function upload(Request $request) {
        $driver = $request->input('driver',env("FILESYSTEM_DRIVER", 'public'));
        $disk = Storage::disk($driver);
        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            // 删除文件并响应
            return $this->deleteFileAndResponse($disk);
        }
        if ($request->file('file')) {
            $file = $request->file;
        } else {
            $file = $request->_file_;
        }
        if (empty($file)) {
            return $this->responseErrorMessage('未检测到文件');
        }
        $md5 = md5_file($file->path());
        //暂时取消 同一文件不覆盖
        $exist = \App\Models\AdminAttachment::where("md5", $md5)->first();
        if (!empty($exist)) {
            return $this->responseUploaded($exist->url,$exist->url);
        }
        // 获取上传的字段名称
        $ext = strtolower($file->extension());
        $allows =  [//限制文件类型 ,
            "image" => ['jpg', 'jpeg', 'png', 'bmp', 'svg', "ico", 'gif', 'webp'],
            "doc" => ['pdf', "doc", 'docx', 'xlsx', 'xls', 'ppt', 'pptx', 'cvs', 'wps', 'txt', 'md', 'rtf'],
            "video" => ['mp4', 'api', 'flv', 'mpg', 'mpeg', 'wmv', '3gp', 'rmvb', 'rm','mov'],
            "audio" => ['mp3', 'wmv', 'amr', 'aud'],
            "file" => ['zip', 'rar', '7z'],
        ];
        $dir = "";
        foreach ($allows as $key => $val) {
            if (in_array($ext, $val)) {
                $dir = $key;
            }
        }
        if ($dir === "" && isset($allows) &&!empty($allows)) {
            return $this->responseErrorMessage("不允许上传的文件类型！");
        }else if ($dir === "") {
            $dir = "file";
        }
        $path="uploads/" . $dir."s/".date("Ym");
        $newName =  $md5 . "." . $file->extension();
        try {
            $result = $file->storeAs($path,  $newName,$driver);
            if ($result) {
                \App\Models\AdminAttachment::insert([
                    'path' => $path.$newName,
                    'type' => $dir,
                    'url' => $disk->url($result),
                    'md5' => $md5,
                    'platform'=>0,
                    'size'=>$file->getSize()/1024,
                    'disk' => $driver,
                    'ext'=>$file->extension(),
                    'uid'=>Admin::user()->id,
                    'created_at' => date("Y-m-d H:i:s"),
                    'updated_at' => date("Y-m-d H:i:s"),
                ]);
            }

            return $result
                ? $this->responseUploaded( $disk->url($result),$disk->url($result) )
                : $this->responseErrorMessage('文件上传失败');
        } catch (\Excetion $e) {
            $this->responseErrorMessage('文件上传失败, ' . $e->getMessage());
        }

    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AdminAttachment(), function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->setActionClass(Grid\Displayers\Actions::class);
            $grid->column('id')->sortable();
            $grid->column('type');
            $grid->column('disk');
            $grid->column('ext');
            $grid->column('size');
            $grid->column('md5');
          //  $grid->column('path')->limit(30);
            $grid->column('url')->display(function(){
                if($this->type=='image'){
                    return  "<img data-action='preview-img' src='".$this->url."' style='max-width:60px;max-height:40px;cursor:pointer' class='img img-thumbnail'/>";;
                }else{
                    return "<a href='".$this->url."' target='_blank'>新窗口打开</a>";
                }
            });
            $grid->column('platform')->using(['0'=>'后台','1'=>'前端']);
            $grid->column('uid');
            $grid->column('created_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AdminAttachment(), function (Show $show) {
            $show->field('id');
            $show->field('type');
            $show->field('disk');
            $show->field('ext');
            $show->field('size');
            $show->field('md5');
            $show->field('path');
            $show->field('url');
            $show->field('platform');
            $show->field('uid');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminAttachment(), function (Form $form) {
            $form->display('id');
            $form->text('type');
            $form->text('disk');
            $form->text('ext');
            $form->text('size');
            $form->text('md5');
            $form->text('path');
            $form->text('url');
            $form->text('platform');
            $form->text('uid');

            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
